<template>
  <div>
    <!--条件查询-->
    <el-form :model="queryForm" style="width: 80% " class="demo-form-inline" label-width="115px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="用户名称">
            <el-input v-model="queryForm.userName" placeholder="请输入用户名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号码">
            <el-input v-model="queryForm.phonenumber" placeholder="请输入手机号码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态">
            <el-select v-model="queryForm.status" placeholder="用户状态" clearable>
              <el-option label="正常" value="0"></el-option>
              <el-option label="停用" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="queryForm.beginDate"
                type="date"
                placeholder="开始时间">
            </el-date-picker>
            <span>至</span>
            <el-date-picker
                v-model="queryForm.endDate"
                type="date"
                placeholder="结束时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <el-button type="primary" @click="query">搜索</el-button>
            <el-button type="primary" @click="resume">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10"></el-col>
        <el-col :span="12">
          <el-button type="primary" @click="openDialog()">新增用户</el-button>
          <el-button type="primary" @click="downExcel()">Excel导出</el-button>
          <el-button type="primary" @click="openEcharts()">生成报表</el-button>
        </el-col>
      </el-row>


    </el-form>

    <!--  用户信息列表-->
    <template>
      <el-table
          class="table-container"
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="userId"
            label="用户编号"
            width="130">
        </el-table-column>
        <el-table-column
            prop="userId"
            label="用户头像"
            width="130">
          <template v-slot="scope">
            <el-image :src="scope.row.avatar"
                      style="width: 80px;height: 90px"></el-image>
          </template>
        </el-table-column>

        <el-table-column
            prop="userName"
            label="用户账号"
            width="150">
        </el-table-column>
        <el-table-column
            prop="nickName"
            label="用户昵称"
            width="150">
        </el-table-column>
        <el-table-column
            prop="deptName"
            label="部门"
            width="180">
          <template v-slot="scope">
            {{ scope.row.dept.deptName }}
          </template>
        </el-table-column>
        <el-table-column
            prop="phonenumber"
            label="手机号码"
            width="180">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="130">
          <template v-slot="scope">
            <el-switch
                v-model="scope.row.status"
                @change="updateStatus(scope.row)"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="0"
                inactive-value="1">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            width="180">
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template v-slot="scope">
            <el-button
                size="mini"
                v-if="scope.row.userId != '1'"
                @click="openDialog(scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                v-if="scope.row.userId != '1'"
                @click="deleteUser( scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--    弹出框-->
    <!-- Form -->
    <el-dialog :title="text" :visible.sync="dialogFormVisible" width="800px">
      <el-form :model="form" label-position="right">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" :label-width="formLabelWidth">
              <el-input v-model="form.nickName" autocomplete="off" placeholder="请输入用户昵称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" :label-width="formLabelWidth" placeholder="">
              <treeselect v-model="form.deptId" :options="deptListTree" :show-count="true" placeholder="请选择归属部门"
                          :normalizer="normalizer"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" :label-width="formLabelWidth">
              <el-input v-model="form.phonenumber" autocomplete="off" placeholder="请输入手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" :label-width="formLabelWidth">
              <el-input v-model="form.email" autocomplete="off" placeholder="请输入邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" :label-width="formLabelWidth">
              <el-input v-model="form.userName" autocomplete="off" placeholder="请输入用户名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" :label-width="formLabelWidth">
              <el-input v-model="form.password" type="password" :disabled="disabled" autocomplete="off"
                        placeholder="请输入用户密码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别" :label-width="formLabelWidth">
              <el-select v-model="form.sex" placeholder="请选择性别" clearable>
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
                <el-option label="未知" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" :label-width="formLabelWidth">
              <el-radio v-model="form.status" label="0">正常</el-radio>
              <el-radio v-model="form.status" label="1">停用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位" :label-width="formLabelWidth">
              <el-select v-model="form.postIds" multiple placeholder="请选择岗位" clearable>
                <el-option v-for="p in postList" :key="p.postId" :label="p.postName" :value="p.postId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" :label-width="formLabelWidth">
              <el-select v-model="form.roleIds" multiple placeholder="请选择岗位" clearable>
                <el-option v-for="p in roleList" :key="p.roleId" :label="p.roleName" :value="p.roleId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.remark" type="textarea" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>


    <!--    分页组件-->
    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryForm.pageNum"
          :page-sizes="[ 5, 7, 10]"
          :page-size="queryForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!--报表对话框-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="65%"
    >
<!--      饼状图容器-->
      <div id="main"
           style="width: 500px;
             height: 400px"
      >
<!--        柱状图容器-->
      </div>
      <div id="zhu"
           style="width: 500px;
           height: 400px">

      </div>

      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="dialogVisible = false">返回</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
//引入组件
import Treeselect from '@riophae/vue-treeselect'
import * as echarts from 'echarts';
//引入样式
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  //注册组件
  components: {Treeselect},
  name: "index",
  data() {
    return {
      //用户列表
      tableData: [],
      //查询条件
      queryForm: {
        pageNum: 1,
        pageSize: 5,
      },
      //总条数
      total: 0,
      //弹出框表单对象
      form: {},
      //弹出框显示
      dialogFormVisible: false,
      //弹出框表单标题宽度
      formLabelWidth: "90px",
      //弹出框标题
      text: "",
      //岗位列表
      postList: [],
      //角色列表
      roleList: [],
      //部门数状列表
      deptListTree: [],
      //多选框选中
      ids: [],
      //禁用标识
      disabled: false,
      //图片上传地址
      uploadUrl: "http://localhost:8004/user/uploadAvatar",
      //头像回显
      imageUrl: "",
      dialogVisible: false,


    }
        ;
  },
  methods: {
    /**
     * 获取用户列表
     */
    getList() {
      this.axios.get("user/list", {params: this.queryForm}).then(r => {
        this.tableData = r.data.data.list;
        this.total = r.data.data.total;
      });
    },
    /**
     * 条件查询
     */
    query() {
      this.queryForm.pageNum = 1;
      this.getList();
    },
    /**
     * 重置条件
     */
    resume() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 5,
      }
      this.getList();
    },
    /**
     * 每页条数变化事件
     */
    handleSizeChange(size) {
      this.queryForm.pageSize = size;
      this.getList();
    },
    /**
     * 当前页数变化事件
     * @param page
     */
    handleCurrentChange(page) {
      this.queryForm.pageNum = page;
      this.getList();
    },


    /**
     * 开关修改用户状态
     * @param row
     */
    updateStatus(row) {
      this.axios.post("user/updateStatus", row).then(r => {
        if (row.status == 0) {
          this.$message.success("用户：" + row.userName + " 的状态已恢复！");
        } else {
          this.$message.error("用户：" + row.userName + " 的状态已禁用！");
        }
        this.getList();
      })
    },
    /**
     * 打开弹出框
     * @param row
     */
    openDialog(row) {
      if (row == null) {
        this.text = "添加用户";
        this.form = {};
        this.imageUrl = "";
        this.disabled = false;
        this.dialogFormVisible = true;
      } else {
        this.text = "编辑用户";
        this.axios.get("user/seleteUser?userId=" + row.userId).then(r => {
          this.form = r.data.data;
          this.imageUrl = r.data.data.avatar;
        });
        this.form = row;
        this.disabled = true;
        this.dialogFormVisible = true;
      }
    },
    saveUser() {
      if (this.form.userId == null) {
        this.axios.post("user/save", this.form).then(r => {
          this.dialogFormVisible = false;
          this.$message.success("新增用户成功!");
          this.getList();
        });
      } else {
        this.axios.post("user/update", this.form).then(r => {
          this.dialogFormVisible = false;
          this.$message.success("修改用户成功!");
          this.getList();
        });


      }

    },
    deleteUser(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.delete("user/delete/" + row.userId).then(r => {
          this.$message.success("删除成功!");
          this.getList();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    /**
     * 获取岗位列表
     */
    getPostList() {
      this.axios.get("user/postList").then(r => {
        this.postList = r.data.data;
      });
    },
    /**
     * 获取角色列表
     */
    getRoleList() {
      this.axios.get("user/roleList").then(r => {
        this.roleList = r.data.data;
      });
    },
    /**
     * 获取部门树状列表
     */
    getdeptListTree() {
      this.axios.get("user/deptListTree").then(r => {
        this.deptListTree = r.data.data;
      });
    },
    /**
     * 自定义部门树状列表键名
     * @param node
     */
    normalizer(node) {
      return {
        id: node.deptId,
        label: node.deptName
      };

    },
    //上传成功回调函数
    handleAvatarSuccess(res) {
      let url = "http://localhost:8004/user/downloadAvatar?fileName=" + res.data;
      this.imageUrl = url;
      this.form.avatar = url;
    },
    //上传前触发事件
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    downExcel() {
      open("http://localhost:8004/user/downExcel");
    },
    /**
     * 点击打开报表弹框
     */
    openEcharts() {
      this.dialogVisible = true;
      //启动一个延时执行任务
      setTimeout(() => {
        //执行饼状图
        this.bingtu();
        this.zhutu()
      }, 10);

    },
    /**
     * 加载饼状图
     */
    bingtu() {
      var chartDom = document.getElementById('main');
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        title: {
          text: '用户数据报表饼状图',
          subtext: 'Fake Data',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: [
              {value: 1048, name: 'Search Engine'},
              {value: 735, name: 'Direct'},
              {value: 580, name: 'Email'},
              {value: 484, name: 'Union Ads'},
              {value: 300, name: 'Video Ads'}
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      option && myChart.setOption(option);
    },
    zhutu() {
      var chartDom = document.getElementById('zhu');
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        title: {
          text: '用户数据报表柱状图',
          subtext: 'Fake Data',
          left: 'center'
        },
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [
              120,
              {
                value: 200,
                itemStyle: {
                  color: '#a90000'
                }
              },
              150,
              80,
              70,
              110,
              130
            ],
            type: 'bar'
          }
        ]
      };

      option && myChart.setOption(option);

    },


    handleSelectionChange(val) {
      this.ids = val.map(item => item.userId);
    },


  },
  created() {
    this.getList();
    this.getPostList();
    this.getRoleList();
    this.getdeptListTree();
  }
};
</script>

<style>

hr {
  width: 80%;
  margin: 0 auto;
  border: none;
  height: 1px;
  background-color: #333;
  margin-top: 20px;
  margin-bottom: 20px;
  text-align: center;
}

.table-container {
  margin: 0 auto; /* 将表格水平居中 */
  max-width: 1300px; /* 设置表格容器的最大宽度 */
  padding-top: 30px;
}

.custom-table {
  width: 100%; /* 设置表格宽度为容器的100% */
  border-collapse: collapse; /* 合并单元格边框 */
  margin: 0 auto; /* 将表格水平居中 */
}

/* 表格样式 */

custom-table td {
  border: 1px solid #ccc; /* 设置单元格边框 */
  padding: 8px; /* 设置单元格内边距 */
  text-align: center;
}

/* 头像上传 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
#main{
  display: inline-block;
}
#zhu{
  display: inline-block;
}
</style>